<?php

namespace App\Admin\Forms;

use Dcat\EasyExcel\Excel;
use Dcat\Admin\Widgets\Form;
use App\Models\RefereeBlack;

class BlackImportForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        $file_path = storage_path('app/public' . $input['import_file']);

        // 读取excel文件
        $data = Excel::import($file_path)->toArray();

        // [
        //     "Sheet1" => [
        //         2 => [
        //             "姓名" => "张三",
        //             "电话" => 123456789,
        //         ],
        //         3 => [
        //             "姓名" => "李四",
        //             "电话" => 987654321,
        //         ],
        //     ],
        // ]

        // 处理数据
        $rows = $data['Sheet1'];
        $arr = [];
        foreach ($rows as $row) {
            $arr[] = [
                'phone' => $row['phone'],
            ];
        }

        RefereeBlack::upsert($arr, ['phone']);

        return $this->response()->success('导入成功')->refresh();
    }
    /**
     * Build a form here.
     */
    public function form()
    {
        // 禁用重置表单按钮
        $this->disableResetButton();
        // 文件上传
        $this->file('import_file', ' ')
            ->disk('public')
            ->accept('xls,xlsx')
            ->uniqueName()
            ->autoUpload()
            ->move('/import')

            ->help('支持xls,xlsx');
    }
}
